package com.wcl.nullmusic.ui.activity;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.wcl.nullmusic.R;
import com.wcl.nullmusic.base.BaseActivity;
import com.wcl.nullmusic.Mp3Info;
import com.wcl.nullmusic.base.BaseAppcation;
import com.wcl.nullmusic.mode.MusicMp3Info;
import com.wcl.nullmusic.mode.PlayMusic;
import com.wcl.nullmusic.ui.adapter.MusicViewPagerAdapter;
import com.wcl.nullmusic.ui.service.NullMusicService;
import com.wcl.nullmusic.utils.BaseUtils;
import com.wcl.nullmusic.utils.ProgressBarUtils;
import com.wcl.nullmusic.utils.ToActivityUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 16/1/8.
 */
public class MusicActivity extends BaseActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    private Mp3Info mp3Info;
    private int currentTime;
    private Toolbar toolbar;
    private ImageView music_pic, music_play, music_prev, music_playMode, music_next, music_list;
    private TextView music_durtion, music_currentTime;
    private SeekBar music_seekBar;
    private SharedPreferences sp;
    private int seekbarProgress;
    private String url;
    private int pos;
    private MusicMp3Info musicMp3Info;
    private PlayMusic playMusic = new PlayMusic();
    private ImageView music_white;
    private ViewPager viewPager;
    private MusicViewPagerAdapter adapter;


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    music_currentTime.setText(BaseUtils.toDurtion(currentPostion));
                    break;
                case 300:
                    music_durtion.setText(BaseUtils.toDurtion(duration));
                    break;
                case 400:
                    music_durtion.setText(BaseUtils.toDurtion(msg.arg1));
                    if (isPlaying) {
                        music_play.setImageResource(R.mipmap.bt_lockscreen_pause_press);
                    } else {
                        music_play.setImageResource(R.mipmap.bt_lockscreen_play_press);
                    }
                    break;
            }

            return false;
        }
    });

    @Override
    protected void conService() {

    }

    @Override
    protected int getLayout() {
        return R.layout.activity_music;
    }

    @Override
    protected void getVaule() {
        //  music_seekBar.setProgress(seekbarProgress);
        Bundle bundle = ToActivityUtils.fromSrc(this);
        if (bundle != null) {
            this.url = bundle.getString("url");
            this.pos = bundle.getInt("pos");
            playMusic = new PlayMusic();
            playMusic.setState(NullMusicService.PLAYER_PLAY);
            playMusic.setUrl(url);
            playMusic.setFlag(true);
            playMusic.setPosition(pos);
            EventBus.getDefault().post(playMusic);
            //  player.onlinePlay(url, pos);
            //  loadData();

        }
    }


    @Override
    protected void initView() {
        //添加Activity到堆栈
        BaseAppcation.getInstance().addActivity(this);

        EventBus.getDefault().register(this);

        ProgressBarUtils.showProgressDialog(this);
        toolbar = findView(R.id.music_toolBar);
      //  music_pic = findView(R.id.music_pic);
        music_play = findView(R.id.music_play);
        music_prev = findView(R.id.music_prev);
        music_playMode = findView(R.id.music_playMode);
        music_next = findView(R.id.music_next);
        music_list = findView(R.id.music_list);
        music_durtion = findView(R.id.music_durtion);
        music_currentTime = findView(R.id.music_currentTime);
        music_seekBar = findView(R.id.music_seekBar);
        viewPager=findView(R.id.music_viewPager);
        this.sp = BaseAppcation.sp;
        seekbarProgress = sp.getInt("seekbarProgress", 0);
        adapter=new MusicViewPagerAdapter(getSupportFragmentManager());
        music_white = (ImageView) findViewById(R.id.music_white);
        // EventBus.getDefault().post(NullMusicService.OBTAIN_MUSIC_ALLINFO);
        EventBus.getDefault().post(NullMusicService.OBTIAN_MUSIC_ISPLAYING);
    }

    @Override
    protected void initData() {
        toolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.mk_ic_web_back);
        viewPager.setAdapter(adapter);

        //player.onlinePlay();
    }

    @Override
    protected void listener() {
        toolbar.setNavigationOnClickListener(this);
        music_play.setOnClickListener(this);
        music_prev.setOnClickListener(this);
        music_playMode.setOnClickListener(this);
        music_next.setOnClickListener(this);
        music_list.setOnClickListener(this);
        music_seekBar.setOnSeekBarChangeListener(this);
    }


    // 按键的监听
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.music_play:
                if (isPlaying) {
                    isPlaying = false;
                    EventBus.getDefault().post(NullMusicService.PLAYER_PAUSE);
                    music_play.setImageResource(R.mipmap.bt_lockscreen_play_press);
                } else {
                    isPlaying = true;
                    EventBus.getDefault().post(NullMusicService.PLAYER_START);
                    music_play.setImageResource(R.mipmap.bt_lockscreen_pause_press);
                }
                break;
            case R.id.music_prev:
                EventBus.getDefault().post(NullMusicService.PLAYER_PREV);
                music_play.setImageResource(R.mipmap.bt_lockscreen_pause_press);
                break;
            case R.id.music_playMode:

                switch (playMode) {
                    case NullMusicService.PLAYER_MODE_ORDER:
                        playMode = NullMusicService.PLAYER_MODE_SINGLE;
                        music_playMode.setImageResource(R.mipmap.bt_list_roundsingle_press);
                        Toast.makeText(MusicActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();
                        break;
                    case NullMusicService.PLAYER_MODE_SINGLE:
                        playMode = NullMusicService.PLAYER_MODE_RANDOM;
                        music_playMode.setImageResource(R.mipmap.bt_list_random_press);
                        Toast.makeText(MusicActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                        break;
                    case NullMusicService.PLAYER_MODE_RANDOM:
                        playMode = NullMusicService.PLAYER_MODE_ORDER;
                        music_playMode.setImageResource(R.mipmap.bt_list_order_press);
                        Toast.makeText(MusicActivity.this, "顺序播放", Toast.LENGTH_SHORT).show();
                        break;
                }
                playMusic = new PlayMusic();
                playMusic.setState(NullMusicService.CHANGE_MUSIC_PLAYERMODE);
                playMusic.setChangePlayerMode(playMode);
                EventBus.getDefault().post(playMusic);
                break;
            case R.id.music_next:
                EventBus.getDefault().post(NullMusicService.PLAYER_NEXT);
                music_play.setImageResource(R.mipmap.bt_lockscreen_pause_press);
                break;
            case R.id.music_list:
                break;
            default:
                finish();
                break;
        }

    }

    private int playMode;
    private int currentPostion;
    private boolean isPlaying;
    private int duration;
    private int musicPosition;

    public void onEvent(Mp3Info mp3Info) {
        Log.i("lp", "mp3INfo 传值");
        this.mp3Info = mp3Info;
//        if (!TextUtils.isEmpty(mp3Info.getPic())) {
//            if (BaseUtils.splitStr(mp3Info.getPic()))
//                Picasso.with(this).load(mp3Info.getPic()).placeholder(R.mipmap.ic_live_voice_press)
//                        .error(R.mipmap.ic_live_voice_press).into(music_pic);
//            else
//                Picasso.with(this).load(new File(mp3Info.getPic())).placeholder(R.mipmap.ic_live_voice_press)
//                        .error(R.mipmap.ic_live_voice_press).into(music_pic);
//        } else
//            music_pic.setImageResource(R.mipmap.ic_live_voice_press);
        EventBus.getDefault().post(mp3Info.getPic());
        toolbar.setTitle("歌名: " + mp3Info.getTitle());
        toolbar.setSubtitle("歌手: " + mp3Info.getArtist());
        music_seekBar.setMax(mp3Info.getDuration());
        Message message = new Message();
        message.arg1 = mp3Info.getDuration();
        message.what = 400;
        handler.sendMessage(message);
        if(music_white.getVisibility()==View.VISIBLE){
        ProgressBarUtils.dismissProgressDialog();}
        music_white.setVisibility(View.GONE);
        if (isPlaying)
            music_play.setImageResource(R.mipmap.bt_playpage_button_pause_press);
        else
            music_play.setImageResource(R.mipmap.bt_playpage_button_play_press);
        // music_durtion.setText(BaseUtils.toDurtion(mp3Info.getDuration()));
    }

    public void onEvent(PlayMusic playMusic) {
        int state = playMusic.getState();
        switch (state) {
            case NullMusicService.SEND_MUSIC_CURRENTPOSITION:
                currentPostion = playMusic.getCurrentPosition();
                if (music_seekBar != null && music_currentTime != null) {
                    music_seekBar.setProgress(currentPostion);
                    handler.sendEmptyMessage(200);
                }
                break;
            case NullMusicService.SEND_MUSIC_PLAYERMODE:
                playMode = playMusic.getCurrentPlayMode();

                break;
            case NullMusicService.SEND_MUSIC_ISPLAYING:
                isPlaying = playMusic.isCurrentIsPlaying();
                if (isPlaying) {
                    EventBus.getDefault().post(NullMusicService.OBTAIN_MUSIC_ALLINFO);
                }
//                if (isPlaying)
//                    main_music_stop.setImageResource(R.mipmap.bt_playpage_button_pause_press);
//                else
//                    main_music_stop.setImageResource(R.mipmap.bt_playpage_button_play_press);
                break;
            case NullMusicService.SEND_MUSIC_DURATION:
                duration = playMusic.getCurrentDuration();
                music_seekBar.setMax(duration);
                handler.sendEmptyMessage(300);
                break;
            case NullMusicService.SEND_MUSIC_POSITION:
                currentPostion = playMusic.getCurrentPosition();
                musicPosition = playMusic.getMusicPosition();
                break;
            case NullMusicService.SEND_MUSIC_ALLINFO:
                currentPostion = playMusic.getCurrentPosition();
                playMode = playMusic.getCurrentPlayMode();
                isPlaying = playMusic.isCurrentIsPlaying();
                duration = playMusic.getCurrentDuration();
                music_seekBar.setProgress(currentPostion);
                music_seekBar.setMax(duration);
                handler.sendEmptyMessage(300);
                switch (playMode) {
                    case NullMusicService.PLAYER_MODE_ORDER:
                        music_playMode.setImageResource(R.mipmap.bt_list_order_press);
                        break;
                    case NullMusicService.PLAYER_MODE_SINGLE:
                        music_playMode.setImageResource(R.mipmap.bt_list_roundsingle_press);
                        break;
                    case NullMusicService.PLAYER_MODE_RANDOM:
                        music_playMode.setImageResource(R.mipmap.bt_list_random_press);
                        break;
                }
                break;
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    // seekBar的监听
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if(fromUser){
            EventBus.getDefault().post(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        playMusic = new PlayMusic();
        playMusic.setState(NullMusicService.CHANGE_MUSIC_CURRENTPOSITION);
        playMusic.setCurrentPosition(seekBar.getProgress());
        EventBus.getDefault().post(playMusic);


    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);

        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("play_mode", playMode);
        editor.putInt("currentPosition", musicPosition);
        editor.putInt("seekbarProgress", currentPostion);
        editor.commit();
        //结束Activity&从栈中移除该Activity
        BaseAppcation.getInstance().finishActivity(this);
        super.onDestroy();
    }
}
